<?php

namespace app\marketing\controller;

use app\common\controller\Adminbase;
use app\model\Goods;
use app\model\GoodsCategory;
use app\model\GoodsColumn as GoodsColumnModel;
use app\model\GoodsColumnGoods;
use app\model\GoodsType;

class Column extends Adminbase
{
    public function index()
    {
        $model = 'GoodsColumn';

        if ($this->request->isAjax()) {
            $map      = $this->buildParamsMap();
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $list   = GoodsColumnModel::where($map)
                ->field('*')
                ->withAttr('top_image', function ($value) {
                    return $value ? get_file_path($value, 1) : '';
                })
                ->page($page, $pageSize)
                ->order('id', 'asc')
                ->select();
            $total  = GoodsColumnModel::where($map)->count();
            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setDataUrl()
            ->setFormUrl('form')
            ->setLimit()
            ->setModel($model)
            ->addTableCheckBox()
            ->setSwitchTpl('switchTpl', 'status')
            ->setSwitchTpl('amplifyTpl', 'top_image')
            ->addTableColumn('id', 'ID', null, null, true)
            ->addTableColumn('title', '栏目名称')
            ->addTableColumn('top_image', '顶部图片', null, '#amplifyTpl')
            ->addTableColumn('start_date', '开始时间')
            ->addTableColumn('end_date', '结束时间')
            ->addTableOperation(230)
            ->setListBtn([
                ['title' => '专栏商品', 'url' => url('goods'), 'class' => 'layui-btn-normal']
            ])
            ->returnForm();

        $this->assign('text', '设置一些产品的专辑，比如端午好礼、过年必备等');
        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');
    }

    public function form()
    {
        $model = 'GoodsColumn';

        $id = $this->request->param('id/d');
        if (isset($id) && $id > 0) {
            $info = GoodsColumnModel::get($id);
            $this->assign('id', $id);
            $this->assign('action', 2);
        } else {
            $info = [
                'sort'        => 50,
                'top_image'   => 36,
                'share_image' => 37,
            ];
        }

//        $default_top   = request()->domain() . '/uploads/images/20250513/8a8c9db124e88a6b1cb3030c4c19528d.jpg';
//        $default_share = request()->domain() . '/uploads/images/20250513/80136ffba72ef6931d3d71f99f5e44cc.jpg';
        //"不上传则使用默认图片：<a href='$default_top' target='_blank'>默认图片</a>"
        $builder = new \app\common\controller\FormBuilder();
        $builder
            ->setModel($model)
            ->setSuccessUrl()
            ->addFormItem('title', 'text', '栏目名称', '', [], 1)
            ->addFormItem('top_image', 'image', '顶部图片', "<span style='color: red;'>尺寸：1500 x 920</span>", [], 1)
            ->addFormItem('share_text', 'text', '转发/发圈文案', '示例：专栏分享', [], 1)
            ->addFormItem('share_image', 'image', '转发/发圈图片', "<span style='color: red;'>尺寸：1600 x 1280</span>", [], 1)
            ->addFormItem('start_date', 'date', '专栏开始时间', '', [], 1)
            ->addFormItem('end_date', 'date', '专栏结束时间', '', [], 1)
            ->setFormData($info)
            ->returnForm();
        $this->assign('module', 'app');
        $this->assign('is_verify', 0);
        return $this->fetch('admin@common/form');
    }

    public function goods()
    {
        $id    = $this->request->param('id/d');
        $model = 'GoodsColumnGoods';

        if ($this->request->isAjax()) {
            $map      = $this->buildParamsMap();
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $list   = GoodsColumnGoods::where($map)
                ->where('column_id', $id)
                ->field('*')
                ->with(['goods'])
                ->withAttr('sale_price', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->page($page, $pageSize)
                ->order('sort', 'asc')
                ->order('id', 'asc')
                ->select();
            $total  = GoodsColumnGoods::where($map)->where('column_id', $id)->count();
            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setLayerBtn([
                ['title' => '添加商品', 'url' => url('select', ['column_id' => $id]), 'class' => '', 'area' => '["95vw", "100vh"]'],
            ])
            ->setReturnBtn('index', '返回专栏列表')
            ->setAddBtn(false)
            ->setDataUrl('goods', ['id' => $id])
            ->setFormUrl('')
            ->setLimit()
            ->setModel($model)
            ->addTableCheckBox()
            ->setSwitchTpl('amplifyTpl', 'image')
            ->addTableColumn('id', 'ID', null, null, true)
            ->addTableColumn('sort', '排序', null, null, false, '', false, '', true)
            ->addTableColumn('title', '标题', 550)
            ->addTableColumn('image', '图片', null, '#amplifyTpl')
            ->addTableColumn('sale_price', '销售价格', 150)
            ->addTableColumn('commission', '佣金', 150)
            ->returnForm();

        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');
    }

    public function select()
    {
        $column_id = $this->request->param('column_id/d');
        $model     = 'Goods';

        if ($this->request->isAjax()) {
            $map      = $this->buildParamsMap();
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $list   = Goods::where($map)
                ->withAttr('source', function ($value, $data) {
                    $text = [1 => "<span class='layui-badge layui-bg-blue'>定向</span>", 2 => "<span class='layui-badge layui-bg-orange'>公开</span>"];
                    return $value ? $text[$value] : '';
                })
                ->withAttr('sale_price', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('share_commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('subsidy_commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('plan_type', function ($value) {
                    $text = [1 => '定向计划', 2 => '公开计划', 3 => '机构定向计划', 4 => '机构普通计划'];
                    return $text[$value] ?? '';
                })
                ->field('*')
                ->page($page, $pageSize)
                ->order('sort asc, id desc')
                ->where('status', 1)
                ->with(['category', 'type'])
                ->select();
            $total  = Goods::where($map)->where('status', 1)->count();
            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }

        $category_list = GoodsCategory::field('id, name')
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
        $category      = [];
        foreach ($category_list as $value) {
            if (!key_exists($value['id'], $category))
                $category[$value['id']] = $value['name'];
        }

        $type_list = GoodsType::field('id, name')
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
        $type      = [];
        foreach ($type_list as $value) {
            if (!key_exists($value['id'], $type))
                $type[$value['id']] = $value['name'];
        }

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setAddBtn(false)
            ->setDelAllBtn(false)
            ->setSelectDataConfirmBtn([
                ['title' => '导入', 'url' => url('import', ['column_id' => $column_id]), 'class' => 'layui-btn-normal', 'msg' => '是否导入选中商品？'],
            ])
            ->setDataUrl('select')
            ->setFormUrl('form')
            ->addSearchItem('title', 'text', '商品标题')
            ->addSearchItem('product_id', 'text', '商品ID')
            ->addSearchItem('shop_appid', 'text', '小店ID')
            ->addSearchItem('category_id', 'select', '商品分类', $category)
            ->addSearchItem('type', 'select', '商品专区', $type)
            ->setLimit()
            ->setModel($model)
            ->addTableCheckBox('left')
            ->setSwitchTpl('switchTpl', 'status')
            ->setSwitchTpl('amplifyTpl', 'image')
            ->addTableColumn('id', 'ID', null, null, true)
            ->addTableColumn('source', '来源', 120)
            ->addTableColumn('plan_type', '计划类型销售价格', 130)
            ->addTableColumn('product_id', '商品ID', 180)
            ->addTableColumn('title', '标题', 550)
            ->addTableColumn('sale_price', '销售价格', 150)
            ->addTableColumn('commission', '佣金', 150)
            ->addTableColumn('image', '图片', null, '#amplifyTpl')
            ->addTableColumn('category_name', '商品分类', 120)
            ->addTableColumn('type_name', '商品专区', 120)
            ->addTableColumn('stock_num', '库存', 120)
            ->addTableColumn('subsidy_commission', '补贴佣金', 150)
            ->returnForm();

        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');
    }

    public function import()
    {
        $column_id = $this->request->param('column_id/d');
        $ids       = $this->request->param('ids');
        if ($ids) {
            $db_ids = GoodsColumnGoods::where('goods_id', 'gt', 0)->column('goods_id');
            $save   = [];
            foreach ($ids as $goods_id) {
                if (!in_array($goods_id, $db_ids)) {
                    $save[] = [
                        'column_id' => $column_id,
                        'goods_id'  => $goods_id,
                    ];
                }
            }
            if ($save) {
                (new GoodsColumnGoods())->saveAll($save);
            }
        }
        return json(['code' => 0, 'msg' => '导入成功', 'data' => ['close' => 1]]);
    }

}
